package com.huitone.gddw.controller.monitoring;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.huitone.gddw.common.ComConstant;
import com.huitone.gddw.log.Log;
import com.huitone.gddw.log.LogResult;
import com.huitone.gddw.log.LogType;
import com.huitone.gddw.service.dto.monitoring.UnifyMonitorDTO;
import com.huitone.gddw.service.dto.monitoring.warn.InnormalEventDTO;
import com.huitone.gddw.service.monitoring.IUnifyMonitorService;
import com.huitone.gddw.service.monitoring.base.IInnormalEventService;

/**
 * 统一监控图
 * @author wuluodan
 *
 */
@Controller
@RequestMapping(value="unifyMon")
public class UnifyMonitorController {

	private final static Logger LOGGER = Logger.getLogger(UnifyMonitorController.class);
	
	@Autowired
	private IUnifyMonitorService unifyMonitorService;
	
	@Autowired
	private IInnormalEventService innormalEventService;
	
	/**
	 * 业务系统
	 * @param request
	 * @return List<UnifyMonitorDTO>
	 */
	@ResponseBody
	@RequestMapping(value="findSrv")
	@Log(logType=LogType.SELECT, content="查询统一监控图")
	public List<UnifyMonitorDTO> findSrv(HttpServletRequest request) {
		try {
			Map<String, Object> params = new HashMap<>();
			params.put("key", request.getParameter("key"));
			return unifyMonitorService.findSrv(params);
		} catch (Exception e) {
			LOGGER.error("查询统一监控图-业务系统信息出现异常：" + e.getMessage(), e);
			request.setAttribute("logResult", LogResult.EXCEPTION);
			return null;
		}
	}
	
	/**
	 * 警告信息
	 * @param request
	 * @return List<InnormalEventDTO>
	 */
	@ResponseBody
	@RequestMapping(value="findWarn")
	public List<InnormalEventDTO> findWarn(HttpServletRequest request) {
		try {
			return innormalEventService.findWarn();
		} catch (Exception e) {
			LOGGER.error("查询统一监控图-警告信息出现异常：" + e.getMessage(), e);
			return null;
		}
	}
	
	/**
	 * 服务器状态
	 * @param request
	 * @return List<Map<String, Object>>
	 */
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value="findService")
	public List<Map<String, Object>> findService(HttpServletRequest request) {
		try {
			Map<String, Object> params = new HashMap<>();
			params.put("objType", request.getParameter("objType"));
			List<String> itemNames = new ArrayList<String>();
			String[] s = request.getParameter("itemNames").toString().split(",");
			for (int i = 0 ; i < s.length ; i ++) {
				itemNames.add(StringUtils.trim(s[i]));
			}
			params.put("itemNames", itemNames);
			List<String> keys = new ArrayList<String>();
			String[] strings = request.getParameter("keys").toString().split(",");
			for (int i = 0 ; i < strings.length ; i ++) {
				keys.add(StringUtils.trim(strings[i]));
			}
			params.put("keys", keys);
			List<UnifyMonitorDTO> result = unifyMonitorService.findService(params);
			
			List<Map<String, Object>> list = new ArrayList<>();
			for (UnifyMonitorDTO unifyMonitorDTO : result) {
				boolean isSame = false;
				for (Map<String, Object> map : list) {
					if (map.get("objId").toString().equals(unifyMonitorDTO.getObjId())) {
						Map<String, Object> mapData = (Map<String, Object>)map.get("data");
						if (unifyMonitorDTO.getApplications() != null && unifyMonitorDTO.getApplications().equals(ComConstant.HDISK)) {
							if (mapData.containsKey(unifyMonitorDTO.getApplications())) {
								Map<String, Object> mapSeq = (Map<String, Object>)mapData.get(unifyMonitorDTO.getApplications());
								if (mapSeq.containsKey(unifyMonitorDTO.getSeq().toString())) {
									Map<String, Object> mapObj = (Map<String, Object>)mapSeq.get(unifyMonitorDTO.getSeq().toString());
									mapObj.put(unifyMonitorDTO.getKey(), unifyMonitorDTO);
								} else {
									Map<String, Object> mapObj = new HashMap<>();
									mapObj.put(unifyMonitorDTO.getKey(), unifyMonitorDTO);
									mapSeq.put(unifyMonitorDTO.getSeq().toString(), mapObj);
								}
							} else {
								Map<String, Object> mapObj = new HashMap<>();
								mapObj.put(unifyMonitorDTO.getKey(), unifyMonitorDTO);
								Map<String, Object> mapSeq = new HashMap<>();
								mapSeq.put(unifyMonitorDTO.getSeq().toString(), mapObj);
								mapData.put(unifyMonitorDTO.getApplications(), mapSeq);
							}
						} else {
							mapData.put(unifyMonitorDTO.getKey(), unifyMonitorDTO);
						}
						isSame = true;
						break;
					}
				}
				if (!isSame) {
					Map<String, Object> map = new HashMap<>();
					map.put("objId", unifyMonitorDTO.getObjId());
					map.put("objName", unifyMonitorDTO.getObjName());
					Map<String, Object> mapData = new HashMap<>();
					if (unifyMonitorDTO.getApplications() != null && unifyMonitorDTO.getApplications().equals(ComConstant.HDISK)) {
						Map<String, Object> mapObj = new HashMap<>();
						mapObj.put(unifyMonitorDTO.getKey(), unifyMonitorDTO);
						Map<String, Object> mapSeq = new HashMap<>();
						mapSeq.put(unifyMonitorDTO.getSeq().toString(), mapObj);
						mapData.put(unifyMonitorDTO.getApplications(), mapSeq);
					} else {
						mapData.put(unifyMonitorDTO.getKey(), unifyMonitorDTO);
					}
					map.put("data", mapData);
					list.add(map);
				}
			}
			
			return list;
		} catch (Exception e) {
			LOGGER.error("查询统一监控图-服务器状态出现异常：" + e.getMessage(), e);
			return null;
		}
	}
	
	/**
	 * 短信平台实时速率
	 * @param request
	 * @return List<UnifyMonitorDTO>
	 */
	@ResponseBody
	@RequestMapping(value="findCurFlow")
	public List<UnifyMonitorDTO> findCurFlow(HttpServletRequest request) {
		try {
			int startDate = Integer.parseInt(request.getParameter("startDate"));
			int endDate = Integer.parseInt(request.getParameter("endDate"));
			int interval = Integer.parseInt(request.getParameter("interval"));
			Map<String, Object> params = new HashMap<>();
			params.put("startDate", startDate - interval);
			params.put("endDate", endDate);
			params.put("interval", interval);
			List<UnifyMonitorDTO> result = unifyMonitorService.findCurFlow(params);
			
			List<UnifyMonitorDTO> list = new ArrayList<>();
			int stime = startDate - interval;
			int etime = stime + interval;
			int j = 0;
			while (etime < endDate) {
				int data = 0;
				if (j > 0) {
					stime = etime;
					etime = stime + interval;
				}
				int i = 0;
				UnifyMonitorDTO um = new UnifyMonitorDTO();
				Iterator<UnifyMonitorDTO> it = result.iterator();
				boolean b = false;
				while (it.hasNext()) {
					um = it.next();
					if (um.getClock() >= stime && um.getClock() < etime) {
						if (0 == i) {
							list.add(um);
							b = true;
						}
						data += Integer.parseInt(um.getValue());
						it.remove();
						i++;
					}
				}
				if (!b) {
					UnifyMonitorDTO e = new UnifyMonitorDTO();
					e.setValue("");
					e.setClock(etime);
					e.setClockTime(new Date((long)(etime) * 1000));
					e.setKey(um.getKey());
					list.add(e);
				} else if (list != null && list.size() > 0 && b) {
					list.get(list.size() - 1).setValue(String.valueOf(data));
					list.get(list.size() - 1).setClockTime(new Date((long)(etime) * 1000));
				}
				j++;
			}
			Collections.reverse(list);
			
			convert(list);
			
			return list;
		} catch (Exception e) {
			LOGGER.error("查询统一监控图-短信平台实时速率出现异常：" + e.getMessage(), e);
			return null;
		}
	}
	
	/**
	 * 短信平台缓存数据
	 * @param request
	 * @return Map<String, Object>
	 */
	@ResponseBody
	@RequestMapping(value="findQueue")
	public Map<String, Object> findQueue(HttpServletRequest request) {
		try {
			int startDate = Integer.parseInt(request.getParameter("startDate"));
			int endDate = Integer.parseInt(request.getParameter("endDate"));
			int interval = Integer.parseInt(request.getParameter("interval"));
			Map<String, Object> params = new HashMap<>();
			params.put("startDate", startDate - interval);
			params.put("endDate", endDate);
			params.put("interval", interval);
			
			List<UnifyMonitorDTO> listCach = unifyMonitorService.findCachelen(params);
			List<UnifyMonitorDTO> listPri = unifyMonitorService.findPri(params);
			
			Map<String, Object> map = new HashMap<>();
			map.put("cachelen", getResult(startDate, endDate, interval, listCach));
			map.put("pri", getResult(startDate, endDate, interval, listPri));
			return map;
		} catch (Exception e) {
			LOGGER.error("查询统一监控图-短信平台缓存数据出现异常：" + e.getMessage(), e);
			return null;
		}
	}
	
	private List<UnifyMonitorDTO> getResult(Integer startDate, Integer endDate, Integer interval, List<UnifyMonitorDTO> result) {
		List<UnifyMonitorDTO> list = new ArrayList<>();
		int stime = startDate - interval;
		int etime = stime + interval;
		int j = 0;
		while (etime < endDate) {
			int data = 0;
			if (j > 0) {
				stime = etime;
				etime = stime + interval;
			}
			int i = 0;
			UnifyMonitorDTO um = new UnifyMonitorDTO();
			Iterator<UnifyMonitorDTO> it = result.iterator();
			boolean b = false;
			while (it.hasNext()) {
				um = it.next();
				if (um.getClock() != null && um.getClock() >= stime && um.getClock() < etime) {
					if (0 == i) {
						list.add(um);
						b = true;
					}
					data += Integer.parseInt(um.getValue());
					it.remove();
					i++;
				}
			}
			if (!b) {
				UnifyMonitorDTO e = new UnifyMonitorDTO();
				e.setValue("");
				e.setClock(etime);
				e.setClockTime(new Date((long)(etime) * 1000));
				e.setKey(um.getKey());
				list.add(e);
			} else if (list != null && list.size() > 0 && b) {
				list.get(list.size() - 1).setValue(String.valueOf(data));
				list.get(list.size() - 1).setClockTime(new Date((long)(etime - 60) * 1000));
			}
			j++;
		}
		Collections.reverse(list);
		
		convert(list);
		
		return list;
	}
	
	/**
	 * 短信平台实时数据
	 * @param request
	 * @return List<UnifyMonitorDTO>
	 */
	@ResponseBody
	@RequestMapping(value="findSmSend")
	public List<UnifyMonitorDTO> findSmSend(HttpServletRequest request) {
		try {
			Map<String, Object> params = new HashMap<>();
			List<UnifyMonitorDTO> list = unifyMonitorService.findSmSend(params);
			convert(list);
			return list;
		} catch (Exception e) {
			LOGGER.error("查询统一监控图-短信平台实时数据出现异常：" + e.getMessage(), e);
			return null;
		}
	}
	
	/**
	 * 各通道短信发送比
	 * @param request
	 * @return List<UnifyMonitorDTO>
	 */
	@ResponseBody
	@RequestMapping(value="findGateSmSend")
	public List<UnifyMonitorDTO> findGateSmSend(HttpServletRequest request) {
		try {
			Map<String, Object> params = new HashMap<>();
			return unifyMonitorService.findGateSmSend(params);
		} catch (Exception e) {
			LOGGER.error("查询统一监控图-各通道短信发送比出现异常：" + e.getMessage(), e);
			return null;
		}
	}
	
	/**
	 * 网关接口发送速率
	 * @param request
	 * @return List<UnifyMonitorDTO>
	 */
	@ResponseBody
	@RequestMapping(value="findGateSpeed")
	public List<UnifyMonitorDTO> findGateSpeed(HttpServletRequest request) {
		try {
			Map<String, Object> params = new HashMap<>();
			params.put("gateLinkIds", request.getParameter("gateLinkIds").split(","));
			return unifyMonitorService.findGateSpeed(params);
		} catch (Exception e) {
			LOGGER.error("查询统一监控图-网关接口发送速率出现异常：" + e.getMessage(), e);
			return null;
		}
	}
	
	/**
	 * 判断是否需要转换单位
	 * @param list
	 */
	private void convert(List<UnifyMonitorDTO> list) {
		// 以最大数判断显示单位
		boolean isW = false;
		for (UnifyMonitorDTO unifyMonitorDTO : list) {
			if (StringUtils.isNotBlank(unifyMonitorDTO.getValue()) && Float.valueOf(unifyMonitorDTO.getValue()) >= 10000f) {
				isW = true;
				break;
			}
		}
		
		// 判断是否转换数字
		if (isW) {
			for (UnifyMonitorDTO unifyMonitorDTO : list) {
				unifyMonitorDTO.setUnits("1");
				unifyMonitorDTO.setValue(StringUtils.isBlank(unifyMonitorDTO.getValue()) ? "" 
						: String.format("%.2f", Float.valueOf(unifyMonitorDTO.getValue()) / 10000f));
			}
		}
	}
	
}
